#!/usr/bin/env python
"""

    genomic_interval_diff.py
    [--log_file PATH]
    [--verbose]

"""

################################################################################
#
#   genomic_interval_diff
#
#
#   Copyright (c) 11/3/2010 Leo Goodstadt
#
#   Permission is hereby granted, free of charge, to any person obtaining a copy
#   of this software and associated documentation files (the "Software"), to deal
#   in the Software without restriction, including without limitation the rights
#   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#   copies of the Software, and to permit persons to whom the Software is
#   furnished to do so, subject to the following conditions:
#
#   The above copyright notice and this permission notice shall be included in
#   all copies or substantial portions of the Software.
#
#   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#   THE SOFTWARE.
#################################################################################

import sys, os

# add self to search path for testing
if __name__ == '__main__':
    exe_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
    module_name = os.path.split(sys.argv[0])[1]
    module_name = os.path.splitext(module_name)[0];
else:
    module_name = __name__

# Use import path from <<../python_modules>>
if __name__ == '__main__':
    sys.path.append(os.path.abspath(os.path.join(exe_path,"/home/lg/python_modules")))



#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   options


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888


if __name__ == '__main__':
    from optparse import OptionParser
    import StringIO

    parser = OptionParser(version="%prog 1.0", usage = "\n\n    %progs [options]")
    parser.add_option("-x", "--interval_file1", dest="interval_file1",
                      metavar="FILE",
                      type="string",
                      help="Name and path of file containing genomic intervals whose "
                      "first three columns must be <contig><tab><beg><end>.")
    parser.add_option("-y", "--interval_file2", dest="interval_file2",
                      metavar="FILE",
                      type="string",
                      help="Name and path of file containing genomic intervals whose "
                      "first three columns must be <contig><tab><beg><end>. The other "
                      "columns are IGNORED!")
    parser.add_option("-d", "--diff_file", dest="diff_file",
                      metavar="FILE",
                      type="string",
                      help="Name and path of file to hold diff of intervals")
    parser.add_option("--one_based_inclusive", dest="one_based_inclusive",
                      action="store_true", default=False,
                      help="Use one based inclusive coordinates.")

    #
    #   general options: verbosity / logging
    #
    parser.add_option("-v", "--verbose", dest = "verbose",
                      action="count", default=0,
                      help="Print more verbose messages for each additional verbose level.")
    parser.add_option("-L", "--log_file", dest="log_file",
                      metavar="FILE",
                      type="string",
                      help="Name and path of log file")
    parser.add_option("--skip_parameter_logging", dest="skip_parameter_logging",
                        action="store_true", default=False,
                        help="Do not print program parameters to log.")
    parser.add_option("--debug", dest="debug",
                        action="count", default=0,
                        help="Set default program parameters in debugging mode.")




    # get help string
    f =StringIO.StringIO()
    parser.print_help(f)
    helpstr = f.getvalue()
    original_args = " ".join(sys.argv)
    (options, remaining_args) = parser.parse_args()

    options.log_file                = os.path.join("genomic_interval_diff_intersection.log")
    options.log_parameters          = True


    #vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    #                                             #
    #   Debug: Change these                       #
    #                                             #
    #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    if options.debug:
        options.one_based_inclusive     = True
        if not options.interval_file1:
            options.interval_file1          = "/data/mus/visitors/lg/ziang_BAC/nodbac.reg"
        if not options.interval_file2:
            options.interval_file2          = "/data/mus/visitors/lg/uncallable/NOD.nc"
        if not options.diff_file:
            options.diff_file       = "nod_bac_callable.regions"

        options.verbose                 = 5
    #vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    #                                             #
    #   Debug: Change these                       #
    #                                             #
    #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    #
    #   mandatory options
    #
    mandatory_options = ["interval_file1", "interval_file2"]
    def check_mandatory_options (options, mandatory_options, helpstr):
        """
        Check if specified mandatory options have b een defined
        """
        missing_options = []
        for o in mandatory_options:
            if not getattr(options, o):
                missing_options.append("--" + o)

        if not len(missing_options):
            return

        raise Exception("Missing mandatory parameter%s: %s.\n\n%s\n\n" %
                        ("s" if len(missing_options) > 1 else "",
                         ", ".join(missing_options),
                         helpstr))
    check_mandatory_options (options, mandatory_options, helpstr)


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   imports


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888


#from json import dumps
from collections import defaultdict
from intervals import t_intervals
from sorted_by_embedded_numbers import sorted_by_embedded_numbers


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Functions


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
#_________________________________________________________________________________________

#   load_intervals
#_________________________________________________________________________________________
def load_intervals (file_name):
    """
    Load data from tab delimited genomic data file inlcuding extra fields
    """
    logger.log(MESSAGE, "Load data from %s" % file_name)
    intervals_by_contig = defaultdict(t_intervals)
    for line in open(file_name):
        if not len(line) or line[0] == '#':
            continue
        data = line.rstrip().split('\t')
        if len(data) < 3:
            logger.warning("Too few fields (<3): %s" % line)
        contig, beg, end = data[0:3]
        beg = int(beg)
        end = int (end)
        if options.one_based_inclusive:
            beg = beg - 1
        extra_fields = data[3:]
        intervals_by_contig[contig].append((beg, end) + tuple(extra_fields))
    return intervals_by_contig

#_________________________________________________________________________________________

#   save_intervals
#_________________________________________________________________________________________
def save_intervals (intervals_by_contig, file_name):
    """
    Load data from tab delimited genomic data file inlcuding extra fields
    """
    logger.log(MESSAGE, "Save intervals to %s" % file_name)
    result_file = open(file_name, "w")
    for contig in sorted_by_embedded_numbers(intervals_by_contig.keys()):
        for items in intervals_by_contig[contig].data:
            result_file.write(contig + "\t")
            if options.one_based_inclusive:
                result_file.write(str(items[0] + 1) + "\t")
            else:
                result_file.write(str(items[0]) + "\t")
            result_file.write("\t".join(map(str, items[1:])) + "\n")

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Logger


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

if __name__ == '__main__':
    import logging
    import logging.handlers

    MESSAGE = 15
    logging.addLevelName(MESSAGE, "MESSAGE")

    def setup_std_logging (logger, log_file, verbose):
        """
        set up logging using programme options
        """
        class debug_filter(logging.Filter):
            """
            Ignore INFO messages
            """
            def filter(self, record):
                return logging.INFO != record.levelno

        class NullHandler(logging.Handler):
            """
            for when there is no logging
            """
            def emit(self, record):
                pass

        # We are interesting in all messages
        logger.setLevel(logging.DEBUG)
        has_handler = False

        # log to file if that is specified
        if log_file and len(log_file):
            handler = logging.FileHandler(log_file, delay=False)
            handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)6s - %(message)s"))
            handler.setLevel(MESSAGE)
            logger.addHandler(handler)
            has_handler = True

        # log to stderr if verbose
        if verbose:
            stderrhandler = logging.StreamHandler(sys.stderr)
            stderrhandler.setFormatter(logging.Formatter("    %(message)s"))
            stderrhandler.setLevel(logging.DEBUG)
            if log_file:
                stderrhandler.addFilter(debug_filter())
            logger.addHandler(stderrhandler)
            has_handler = True

        # no logging
        if not has_handler:
            logger.addHandler(NullHandler())


    #
    #   set up log
    #
    logger = logging.getLogger(module_name)
    setup_std_logging(logger, options.log_file, options.verbose)


    #
    #   log programme parameters
    #
    if not options.skip_parameter_logging:
        programme_name = os.path.split(sys.argv[0])[1]
        logger.info("%s %s" % (programme_name, original_args))

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Main logic


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
if __name__ == '__main__':
#   debug code not run if called as a module
#

    intervals1_by_contig = load_intervals (options.interval_file1)
    intervals2_by_contig = load_intervals (options.interval_file2)

    logger.debug("Diff...")
    intersecting_intervals = dict()
    for contig in intervals1_by_contig:
        if contig not in intervals2_by_contig:
            continue
        intersecting_intervals[contig] = intervals1_by_contig[contig].subtract(intervals2_by_contig[contig])

    save_intervals(intersecting_intervals, options.diff_file)

